﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace SOEI.Solution.EntityFrameworkCore.EntityMapper
{
    public static class AbpMapperExtension
    {
        /// <summary>
        /// 这个方法根据选择调用 处理特性映射老的数据表
        /// </summary>
        /// <param name="builder"></param>
        public static void SetAttrbuteEntity<TEntity>(this EntityTypeBuilder<TEntity> builder) where TEntity : class
        {
            // 处理表映射(使用特性处理)
            var tbAttrs = builder.Metadata.ClrType.GetCustomAttributes(typeof(TableAttribute), true);
            var tbattr = tbAttrs.FirstOrDefault() as TableAttribute;
            if (tbAttrs.Length > 0)
                builder.ToTable(tbattr.Name);

            // 处理属性的映射(使用特性处理)
            var properties = builder.Metadata.GetProperties();
            foreach (var prop in properties)
            {
                var attrs = prop.PropertyInfo.GetCustomAttributes(typeof(ColumnAttribute), true);
                var attr = attrs.FirstOrDefault() as ColumnAttribute;
                if (attrs.Length > 0)
                    builder.Property(prop.Name).HasColumnName(attr.Name);
            }
        }
    }
}
